#include "unp.h"
#include <time.h>

int main(int argc, char** argv){
	int listenfd, connfd;						/* listen sockfd and connect sockfd */
	socklen_t len;								/* used to store client socket address's length */
	struct sockaddr_in servaddr, cliaddr;		/* we set servaddr. cliaddr will be filled by accept */
	time_t ticks;
	char buf[MAXLINE];

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(13);				/* port address in servaddr are big-endian. Use htons to convert a 
												   little-endian 16-bit number to big-endian one. */
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);	/* operation of ip address are like port address */

	
	if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)	/* AF_INET and SOCK_STREAM determine this a tcp socket */
		err_sys("socket error");

	if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
		err_sys("bind error");

	if( listen(listenfd, 100) < 0)
		err_sys("listen error");

	while(1){
		len = sizeof(cliaddr);
		connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &len);
		if(connfd <0)
			err_sys("accept error");
		printf("connection from %s, port %d\n",
				inet_ntoa(cliaddr.sin_addr),
				ntohs(cliaddr.sin_port));
		ticks = time(0);
		snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&ticks));
		if (write(connfd, buf, strlen(buf)) <0)
			err_sys("write error");

		if( close(connfd) < 0 )
			err_sys("close error");
	}

}
